<template>
  <el-table-column
    v-for="item in list"
    v-bind="emitChild(item)"
    :min-width="getPx(item.minWidth !== void 0 ? item.minWidth : 80)"
    :width="getPx(item?.width)"
    :prop="item.key"
    :label="typeof item.label === 'function' ? item.label() : $t(item.label)"
  >
    <template v-if="item.children && item.children.length">
      {{ '' }}
      <z-table-column :list="item.children" :i18n="i18n" :i18n-prefix="i18nPrefix">
      </z-table-column>
    </template>

    <template #default="scope" v-if="item.btns">
      <div class="z-table-column--btns">
        <template v-for="btn in item.btns">
          <el-link
            v-if="typeof btn.hidden === 'function' ? !btn.hidden(scope, btn) : !btn.hidden"
            v-bind="btn"
            @click="onBtnClick(scope, btn)"
            >{{ $t(btn.label) }}</el-link
          >
        </template>
      </div>
    </template>

    <template #default="scope" v-if="item.render">
      <Component :is="item.render(scope, scope.row[item.key || ''])" />
    </template>
  </el-table-column>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
import type { Props, Btn } from './type'

defineOptions({
  name: 'z-table-column'
})

const props = defineProps<Props>()
const { t } = useI18n()
const $t = (text: string = '') => {
  return props.i18n && text ? t((props.i18nPrefix ? props.i18nPrefix + '.' : '') + text) : text
}

// 获取转换像素
const getPx = (px?: number | string, maxWidth = 1920) => {
  if (px == void 0) return
  if (typeof px === 'string') {
    return px
  }
  const drp = document.body.clientWidth / maxWidth
  return px * drp
}

// 点击事件
const onBtnClick = (scope: AnyObject, btn: Btn) => {
  if (typeof btn.click === 'function') {
    btn.click(scope, toRaw(btn))
  }
}

// 剔除  children 字段
// 防止控制台警告
const emitChild = (item: import('./type').ColumnItem) => {
  const obj = {
    ...item
  }
  delete obj.children
  return obj
}
</script>

<style lang="scss">
@use './style.scss';
</style>
